package com.webdrider.manager.action.snippet;

import java.util.List;

import com.common.dao.interfaces.IDao;
import com.common.dao.util.Criteria;
import com.common.manager.abstracts.AbstractManager;
import com.common.security.exceptions.DatabaseException;
import com.common.security.exceptions.ManagerException;
import com.webdrider.dao.action.snippet.TagDao;
import com.webdrider.dao.interfaces.ITagDao;
import com.webdrider.manager.interfaces.ITagManager;
import com.webdrider.model.action.snippet.Tag;
import com.webdrider.security.exceptions.SnippetException;

public class TagManager extends AbstractManager<Tag> implements ITagManager {

	private ITagDao dao;
	
	public TagManager() {
		dao = new TagDao();
	}
	
	@Override
	protected IDao<Tag> getDao() {
		return dao;
	}

	public boolean exist(String value) throws ManagerException {
		try {
			Criteria criteria = new Criteria(Tag.VALUE, value, true);
			boolean exist = dao.getByCriteria(criteria).size() > 0;

			return exist;
		} catch (DatabaseException e) {
			throw new ManagerException(ManagerException.DATABASE_EXCEPTION);
		}
	}
	
	public Tag getTag(String value) throws ManagerException, SnippetException {
		try {
			Criteria criteria = new Criteria(Tag.VALUE, value, true);
			List<Tag> tags = dao.getByCriteria(criteria);
			
			if (tags.size() == 0) {
				throw new SnippetException(SnippetException.TAG_NOT_FOUND);
			} else if (tags.size() == 1) {
				return tags.get(0);
			} else {
				throw new SnippetException(SnippetException.MULTIPLE_TAGS_FOUND);
			}
		} catch (DatabaseException e) {
			throw new ManagerException(ManagerException.DATABASE_EXCEPTION);
		}
	}
}
